package com.xfcycle.zebrabikegp.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.assist.BlueToothAssist;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.constant.WebConstant;
import com.xfcycle.zebrabikegp.util.EncryptStringUtil;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 修改用户邮箱地址
 */
public class MyProfileEmailActivity extends RootActivity {

    private static final String TAG = "MyProfileEmail";

    private ImageView iv_my_profile_email_back;

    private TextView tv_my_profile_email_save;

    private EditText et_my_profile_email_content;
    private EditText et_my_profile_email_password;
    private EditText et_my_profile_email_captcha;

    private Button btn_me_profile_email_send_code;

    private String str_email_address;
    private String uid;

    private boolean threadRun;
    private Message timeMsg;

    /**
     * 主线程修改UI
     */
    private Handler handlerChangeBt = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (threadRun) {
                        if ("0s".equals(msg.obj)) {
                            stopTimeKeepingThread();
                            return;
                        }
                        btn_me_profile_email_send_code.setText(msg.obj + "");
                    }
                }
            });
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_profile_email);

        Bundle bundle = getIntent().getExtras();
        uid = bundle.getString("uid");

        initView();
        initViewListener();
    }

    /**
     * 初始化组件
     */
    private void initView() {
        iv_my_profile_email_back = (ImageView) findViewById(R.id.iv_my_profile_email_back);

        tv_my_profile_email_save = (TextView) findViewById(R.id.tv_my_profile_email_save);

        et_my_profile_email_content = (EditText) findViewById(R.id.et_my_profile_email_content);
        et_my_profile_email_password = (EditText) findViewById(R.id.et_my_profile_email_password);
        et_my_profile_email_captcha = (EditText) findViewById(R.id.et_my_profile_email_captcha);

        btn_me_profile_email_send_code = (Button) findViewById(R.id.btn_my_profile_email_send_code);

        timeMsg = new Message();
        threadRun = true;
    }

    /**
     * 初始化监听事件
     */
    private void initViewListener() {
        //回退按钮点击事件监听
        iv_my_profile_email_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                closeActivity();
            }
        });

        //修改用户手机号到服务器
        tv_my_profile_email_save.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Editable email_address = et_my_profile_email_content.getText();
                Editable password = et_my_profile_email_password.getText();
                Editable captcha = et_my_profile_email_captcha.getText();

                if (null == email_address || "".equals(email_address.toString())
                        || null == password || "".equals(password.toString())
                        || null == captcha || "".equals(captcha.toString())) {
                    Log.e(TAG, "onClick: ----------------- 需要的数据不全");
                    return;
                }
                str_email_address = email_address.toString();
                //设置用户的邮箱
                Map<String, String> params_change_email = new HashMap<>();
                params_change_email.put(WebConstant.CHANGE_EMAIL_PATH_PARAM_KEY_EMAIL, str_email_address);
                params_change_email.put(WebConstant.CHANGE_EMAIL_PATH_PARAM_KEY_PASSWORD, EncryptStringUtil.getMd5(password.toString()));
                params_change_email.put(WebConstant.CHANGE_EMAIL_PATH_PARAM_KEY_CODE, captcha.toString());
                new GetJsonFromWebJob(WebConstant.CHANGE_EMAIL_PATH_ONE + uid + WebConstant.CHANGE_EMAIL_PATH_TWO, WebConstant.PUT, params_change_email, REQUEST_SIGN_CHANGE_EMAIL_ADDRESS, MyProfileEmailActivity.this).start();
            }
        });

        //获取验证码
        btn_me_profile_email_send_code.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是否输入邮箱地址
                if (null == et_my_profile_email_content.getText() || "".equals(et_my_profile_email_content.getText().toString())) {
                    Toast.makeText(MyProfileEmailActivity.this.getApplicationContext(), ToastConstant.INPUT_EMAIL_ADDRESS_FIRST, Toast.LENGTH_SHORT).show();
                    return;
                }
                String new_email_address = et_my_profile_email_content.getText().toString();
                //请求验证码按钮不可按
                btn_me_profile_email_send_code.setEnabled(false);

                //向服务器请求邮箱验证码
                Map<String, String> params_response_code = new HashMap<>();
                params_response_code.put("check", "2");
                new GetJsonFromWebJob(WebConstant.GET_EMAIL_AUTH_PATH + new_email_address, WebConstant.POST, params_response_code, REQUEST_SIGN_GET_EMAIL_CAPTCHA, MyProfileEmailActivity.this).start();

                //开启计时线程，修改验证码发送的时机
                threadRun = true;
                new TimeKeepingThread().start();
            }
        });

        //输入邮箱 内容监听
        et_my_profile_email_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!"Send code".equals(btn_me_profile_email_send_code)) {
                    btn_me_profile_email_send_code.setText("Send code");
                    threadRun = false;
                }
                btn_me_profile_email_send_code.setEnabled(true);
            }
        });
    }

    /**
     * 处理从网络获取的数据
     *
     * @param webMsg
     */
    @Override
    public void dealDataFromWeb(Message webMsg) {
        super.dealDataFromWeb(webMsg);

        String webResult = webMsg.obj.toString();
        int webSign = webMsg.what;

        //判断获取验证码 邮箱地址已使用
        if (webResult.contains("user already existed")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.EMAIL_HAS_BEEN_USED, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "dealDataFromWeb: --------------------- 邮箱地址已使用");
            stopTimeKeepingThread();
            return;
        }

        //判断缺少参数
        if (webResult.contains("MissingParameter")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.NETWORK_FAILURE, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "dealDataFromWeb: --------------------- 缺少参数");
            stopTimeKeepingThread();
            return;
        }

        //用户不存在或密码错误
        if (webResult.contains("none user or incorrect password")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.NONE_USER_OR_PASSWORD_WRONG, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "dealDataFromWeb: --------------------- 用户不存在或密码错误");
            stopTimeKeepingThread();
            return;
        }
        //判断验证码已过期
        if (webResult.contains("verification code expired")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.CAPTCHA_EXPIRE, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "dealDataFromWeb: --------------------- 验证码已过期");
            stopTimeKeepingThread();
            return;
        }
        //判断验证码不匹配
        if (webResult.contains("verification code mismatched")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.CAPTCHA_MISMATCH, Toast.LENGTH_SHORT).show();
            Log.e(TAG, "dealDataFromWeb: --------------------- 验证码不匹配");
            stopTimeKeepingThread();
            return;
        }

        //验证码验证成功，进行页面跳转
        if (REQUEST_SIGN_CHANGE_EMAIL_ADDRESS == webSign && "".equals(webResult)) {
            Bundle backBundle = new Bundle();
            backBundle.putString("email_address",str_email_address);
            setResult(RESULT_OK,new Intent().putExtras(backBundle));
            finish();
        }

        //判断在其他设备登陆
        if (webMsg.obj.toString().contains("you are signed in at another location") && REQUEST_SIGN_LOGOUT != webMsg.what) {
            //断开连接
            HandleDataByBLEUtil.disConnectDevice();
            //改变蓝牙辅助判断类的值
            BlueToothAssist.isConnect = false;
            BlueToothAssist.currentConnectBikeId = null;

            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(ToastConstant.DIALOG_WARNING);
                builder.setMessage(ToastConstant.OTHER_DEVICE_LOGIN);

                builder.setPositiveButton(ToastConstant.DIALOG_I_KNOW, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //回到登录界面
                        activityChange(LOGIN_ACTIVITY, null, null);
                        HandleDataByBLEUtil.disConnectDevice();
                    }

                });
                //展示提示框
                builder.create().show();
            }catch (Exception e){
                Toast.makeText(this.getApplicationContext(), ToastConstant.OTHER_DEVICE_LOGIN, Toast.LENGTH_LONG).show();
                activityChange(LOGIN_ACTIVITY, null, null);
                HandleDataByBLEUtil.disConnectDevice();
            }
            return;
        }
    }

    /**
     * 验证码重发计时线程
     */
    class TimeKeepingThread extends Thread {
        @Override
        public void run() {
            for (int i = 60; i >= 0; i--) {
                if (threadRun) {
                    SystemClock.sleep(990);
                    timeMsg.obj = i + "s";
                    handlerChangeBt.handleMessage(timeMsg);
                }
            }
        }

    }

    private void stopTimeKeepingThread() {
        threadRun = false;
        btn_me_profile_email_send_code.setEnabled(true);
        btn_me_profile_email_send_code.setText("Send code");
    }
}
